<?php
/**
 * 领取鸡蛋白程序
 * @access  public
 * @todo    鸡蛋白抢购
 * @version 20150927 wnewstar
 * @return  $return  array   返回结果数据
 */

function get_glair() {
    // 缓存版本
    $version = date('md');
    // 用户ID
    $user_id = ! empty($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
    // 抢购数量
    $act_num = intval($_POST['act_num']);
    // 抢购结果
    $return = array('error'=>0,'message'=>'');
    // 当前时间
    $time = time();
    // 缓存对象
    $glair_cache = M();
    // 计数器对象
    $glair_counter = C();
    // 缓存有效时间
    $cache_exp_time = 7200;
    /* 未登录用户 */
    if (empty($user_id)) {
        $return['error'] = 8000;
        $return['message'] = "请登录后再领取";
        return $return;
    }
    /* 时间未到 */
    $date = intval(Date('Hi'));
    if($date < 2230 || $date > 2329) {
        $return['error'] = 8012;
        $return['message'] = "时间未到";
        return $return;
    }

    /** 
     * 开始抢购 
     */

    // 查看库存数量，库存不足，抢购失败
    $glair_all_num = intval($glair_counter->getCounter('glair_stock_' . $version));
    if($glair_all_num <= 0) {
        $return['error']   = 8003;
        $return['message'] = "鸡蛋白已经被抢完啦！";
    } else {
        // 获取用户已抢购数量
        $user_get_num = intval($glair_cache->get('glair_user_' . $version . '_' . $user_id));
        if(! empty($user_get_num)) {
            // 如果已经抢购了25瓶，返回提示信息
            if($user_get_num >= 25) {
                $return['error']   = 8003;
                $return['message'] = "抢购数量已达上限！";
            } else {
                // 预期抢购总数量
                $temp_num = $user_get_num + $act_num;
                if($temp_num > 25) {
                    $all_num = 25;
                } else {
                    $all_num = $temp_num;
                }
                // 可抢购数量
                $act_num = $all_num - $user_get_num;
                // 库存数量和可抢购数量对比，库存小于可抢购数量，则抢购数量为库存数量
                if($glair_all_num < $act_num) {
                    $act_num = $glair_all_num;
                    $all_num = $user_get_num + $act_num;
                }
                // 替换用户已抢购数量
                $num_act = 'repalce';
            }
        } else {
            // 记录参与领取人数
            $glair_counter->inCounter('glair_buy_user_count_' . $version);
            // 可抢购数量
            if($act_num > 25) {
                $act_num = 25;
            }
            // 库存数量和可抢购数量对比，库存小于可抢购数量，则抢购数量为库存数量
            if($glair_all_num < $act_num) {
                $act_num = $glair_all_num;
            }
            // 已抢购总数量为可抢购数量
            $all_num = $act_num;
            // 新增用户已抢购数量
            $num_act = 'add';
        }
        // 减库存
        if($glair_counter->deCounter('glair_stock_' . $version, $act_num, $cache_exp_time)) {
            if($glair_cache->$num_act('glair_user_' . $version . '_' . $user_id, $act_num, $cache_exp_time)) {
                $return['error']   = 0;
                $return['message'] = "抢购成功！";   
            } else {
                $return['error']   = 8003;
                $return['message'] = "抢购失败！";
            }
        } else {
            $return['error']   = 8003;
            $return['message'] = "抢购失败！";
        }
    }
    return $return;
}

/**
 * 领取鸡蛋白包邮券
 * @access  public
 * @return  $return     array   返回提示数据
 */

function get_glairBaoyou(){
    $version = date('md');
    $user_id = !empty($_SESSION['user_id'])?$_SESSION['user_id']:0;
    $return = array('error'=>0,'message'=>'','content'=>'');
    /* 开始领取 */
    $user_get_num = $glair_cache->get('userGlair' . $version . $user_id); // 获取用户领取状态
    if (!empty($user_get_num) && $user_get_num >= 1) {
        $glair_cache->set('userGlairBaoyou' . $version . $user_id, '1', 20800);// 标记已抢(抢到)
        Q()->append('queueGlairBaoyou'.$version, "$user_id");
        $return['error'] = 0;
        $return['message'] = '成功领取';
    } else {
        $return['error'] = 1;
        $return['message'] = '领取鸡蛋白包邮券失败，已被领取完';
    }
    return $return;
}

/**
 * 兑换鸡蛋白
 * @param  string $code 兑换码
 * @return array        返回数据
 */
function exchangeGlair($code=0){

    $userId = !empty($_SESSION['user_id'])?$_SESSION['user_id']:'';
    $time = time();
    if (empty($userId)) {
        $return['error'] = 8000;
        $return['message']="请登录后再领取";
        return $return;
    }
    if (empty($code)) {
        $return['error'] = 8201;
        $return['message']="请输入兑换码";
        return $return;
    }

    $sql =  " SELECT get_start_time FROM ".$GLOBALS['ecs']->table('coupon').
            " WHERE  coupon_code ='$code'";
    $coupon = $GLOBALS['db']->getOne($sql);
    if (empty($coupon)) {
        $return['error'] = 8202;
        $return['message']="领取码错误";
        return $return;
    }

    $sql =  " SELECT count(*) FROM ".$GLOBALS['ecs']->table('coupon').
            " WHERE  get_start_time ='$coupon' AND user_id = '$userId'";
    $isGet =$GLOBALS['db']->getOne($sql);
    if (!empty($isGet)) {
        $return['error']   = 8203;
        $return['message'] = "你已领取成功无法重复领取";
        return $return;
    }

    include_once(ROOT_PATH . 'includes/classLock.php');
     $lock = new classLock;
     if ($lock->lock('exchangeGlair')) {

        $sql = " SELECT coupon_id FROM ".$GLOBALS['ecs']->table('coupon').
                " WHERE coupon_code ='$code' AND user_id = '0' AND get_start_time < '$time' AND get_end_time > '$time' ";
        $couponId = $GLOBALS['db']->getOne($sql);
        if (empty($couponId)) {
            $lock->unlock('exchangeGlair');
            $return['error']   = 8204;
            $return['message'] = "领取码已使用或过期";
            return $return;
        }

        $sql = " UPDATE ".$GLOBALS['ecs']->table('coupon').
               " SET user_id = '$userId' , exchange_time = '$time' ,is_exchange = '1'".
               " WHERE coupon_id = '$couponId'";
        $GLOBALS['db']->query($sql);
        /* 查询礼包信息 */
        $sql  = " SELECT name, original_price, parent_id, extension_code, price, is_sale FROM " . $GLOBALS['ecs']->table('activity') .
                " WHERE min_price = '888' AND extension_code = 'gift'";
        $info = $GLOBALS['db']->getRow($sql);

        $sql  = " INSERT INTO ".$GLOBALS['ecs']->table('cart').
                " ( user_id,goods_name, market_price, extension_code, extension_id,is_gift,area_id, add_time,goods_price,goods_number,parent_id)".
                " VALUES ";
        $sql  = $sql ."('$userId','".$info['name']."','".$info['original_price']."','gift','".$info['parent_id']."',1,'3','".time()."','".$info['price']."','2','".$info['parent_id']."')";
        $GLOBALS['db']->query($sql);
        // /* 修改礼包数量 */
        $sql = " UPDATE " . $GLOBALS['ecs']->table('activity_stock') .
               " SET valid_number = valid_number - 2,cart_number = (cart_number+2)".
               " WHERE parent_id = '$info[parent_id]' AND area_id = '3'";
        $GLOBALS['db']->query($sql);

        $lock->unlock('exchangeGlair');
        $return['error']   = 0;
        $return['message'] = "领取成功";
        return $return;
     }else{
        $return['error']   = 8222;
        $return['message'] = "请勿频繁提交";
        return $return;
     }
}

/*冒泡排序算法*/
function bubbleSort2($numbers,$key='num') {
        foreach ($numbers as $key_1 => $value_1) {

            foreach ($numbers as $key_2 => $value_2) {
                    if (!empty($numbers[$key_2 + 1][$key])) {
                        if ($numbers[$key_2][$key] < $numbers[$key_2 + 1][$key]) {
                            $temp = $numbers[$key_2];
                            $numbers[$key_2] = $numbers[$key_2 + 1];
                            $numbers[$key_2 + 1] = $temp;
                        }
                    }
            }

        }
    return $numbers;
}
